package com.yudean.esb.service.impl;

import com.yudean.esb.dao.erp.ErpAccountDao;
import com.yudean.esb.dao.erp.ErpIdsInvVoucherDao;
import com.yudean.esb.dao.mds.*;
import com.yudean.esb.domain.erp.ErpIdsInvVoucher;
import com.yudean.esb.domain.mds.*;
import com.yudean.esb.service.AccountDAO;
import com.yudean.esb.security.SysAppUserService;
import com.yudean.esb.util.PageUtil;
import com.yudean.esb.util.StringUtil;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jws.WebService;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.apache.commons.lang3.StringUtils.trimToEmpty;

@WebService(endpointInterface = "com.yudean.esb.service.AccountDAO", serviceName = "AccountDAOService",targetNamespace = "http://service.esb.yudean.com/")
@Service
public class AccountDAOImpl implements AccountDAO {
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(AccountDAOImpl.class);

    @Resource
    private SysAppUserService sysAppUserService;
    @Resource
    private ErpAccountDao erpAccountDao;

    static String perCompCode = "";
    static String perUserName = "";
    static String perPasswd = "";

    /**
     * @param ccid  科目组合Id
     * @return      根据ccid查询科目组合
     */
    @SuppressWarnings("rawtypes")
    @Override
    public String getAccountCombinationsByCCId(String ccid) {
        List list = erpAccountDao.selectByCcid(Long.valueOf(ccid));
        return this.listToAccountCombinationsXML(list);
    }

    /**
     * @param CompCode  公司编码
     * @return          根据公司编码查询科目组合
     */
    @SuppressWarnings("rawtypes")
    public String getAccountCombinationsByCompCode(String CompCode) {
        List list = erpAccountDao.findAccountCombinationsByCompCode(CompCode);
        return this.listToAccountCombinationsXML(list);
    }

    /**
     * @param pageNo    页码
     * @param pageSize  分页大小
     * @return          查询所有科目组合
     */
    @Override
    public String getAllAccountCombinations(String pageNo, String pageSize, String username, String password) {
        log.info("getAllAccountCombinations():request:{,username-{}}", username);
        if ((username != "" && perCompCode.equals("YDZ") && perUserName.equals(username) && perPasswd.equals(password))
                || sysAppUserService.hasPermit("YDZ", username, password)) {
            perCompCode = "YDZ";
            perUserName = username;
            perPasswd = password;
        } else {
            return sysAppUserService.getErrMsg();
        }

        final int pageNoInt = PageUtil.handlePageNo(pageNo);
        final int pageSizeInt = PageUtil.handlePageSize(pageSize);


        List list = null;
        try {
            list = erpAccountDao.findAllAccountCombinations(pageNoInt,pageSizeInt);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return listToAccountCombinationsXML(list, getAccountCombinationCount(), pageNoInt, pageSizeInt);
    }

    /**
     * @return  查询记录总数（MDS_ACCOUNT_COMBINATIONS）
     */
    private long getAccountCombinationCount() {
        return erpAccountDao.getAccountCombinationCount();
    }

    /**
     * @param CompCode      公司三字码
     * @param acctCode      科目编码
     * @return              根据公司编码和科目编码查询科目组合
     */
    @SuppressWarnings("rawtypes")
    @Override
    public String getAccountCombinationsByCompCodeandAcctCode(String CompCode,
                                                              String acctCode) {
        List list = erpAccountDao.getAccountCombinationsByCompCodeandAcctCode(CompCode,acctCode);
        return this.listToAccountCombinationsXML(list);
    }

    /**
     * @param AcctCode      科目编码
     * @return              根据科目编码查询科目
     */
    @SuppressWarnings("rawtypes")
    @Override
    public String getAccountByAcctCode(String AcctCode) {
        List list = erpAccountDao.getAccountByAcctCode(AcctCode);
        return this.listToAccountXML(list);
    }

    /**
     * @return       获取所有科目
     */
    @SuppressWarnings("rawtypes")
    @Override
    public String getAllAccount() {
        List list = erpAccountDao.getAllAccount();
        return this.listToAccountXML(list);
    }

    /**
     * @return      获取所有一级科目
     */
    @SuppressWarnings("rawtypes")
    @Override
    public String getAllFatherAccount() {
        List list = erpAccountDao.getAllFatherAccount();
        return this.listToAccountXML(list);
    }

    /**
     * @param fatherCode    父科目
     * @return              根据父科目获取子科目
     */
    @SuppressWarnings("rawtypes")
    @Override
    public String getSubAccountByFatherCode(String fatherCode) {
        fatherCode += "__";
        List list = erpAccountDao.getSubAccountByFatherCode(fatherCode);
        return this.listToAccountXML(list);
    }

    /**
     * @param CompCode  公司三字码
     * @return          根据公司编码查询子科目
     */
    @SuppressWarnings("rawtypes")
    @Override
    public String getAccountSubByCompCode(String CompCode) {
        List list = erpAccountDao.getAccountSubByCompCode(CompCode);
        return this.listToAccountSubXML(list);
    }

    /**
     * @param pageNo   页码
     * @param pageSize 分页大小
     * @return          查询所有子科目(分页方式)
     */
    @Override
    public String getAllSubAccount(String pageNo, String pageSize, String username, String password) {
        log.info("getAllSubAccount():request:{,username-{}}", username);
        if ((username != "" && perCompCode.equals("YDZ") && perUserName.equals(username) && perPasswd.equals(password))
                || sysAppUserService.hasPermit("YDZ", username, password)) {
            perCompCode = "YDZ";
            perUserName = username;
            perPasswd = password;
        } else {
            return sysAppUserService.getErrMsg();
        }
        final int pageNoInt = PageUtil.handlePageNo(pageNo);
        final int pageSizeInt = PageUtil.handlePageSize(pageSize);
        List list = null;
        try {
            list = erpAccountDao.getAllSubAccount(pageNoInt,pageSizeInt);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return listToAccountSubXML(list, getSubAccountCount(), pageNoInt, pageSizeInt);
    }

    /**
     * @return  查询子科目记录总数
     */
    private long getSubAccountCount() {
        return erpAccountDao.getSubAccountCount();
    }

    /**
     *
     * @param AcctCodeSub     子科目编码
     * @return                根据子科目编码查询子科目
     */
    @SuppressWarnings("rawtypes")
    @Override
    public String getAccountSubByAcctCodeSub(String AcctCodeSub) {
        List list = erpAccountDao.getAccountSubByAcctCodeSub(AcctCodeSub);
        return this.listToAccountSubXML(list);
    }

    // 根据月份和三字码查找某公司余额查询出
    @SuppressWarnings({"unchecked", "rawtypes"})
    public String getBalanceByPeriodName(final String periodName,
                                         final String segment1, String username, String password) {
        if ((username != "" && perCompCode.equals(segment1) && perUserName.equals(username) && perPasswd.equals(password))
                || sysAppUserService.hasPermit(segment1, username, password)) {
            perCompCode = segment1;
            perUserName = username;
            perPasswd = password;
        } else {
            return sysAppUserService.getErrMsg();
        }
        List list = erpAccountDao.getBalanceByPeriodName(periodName,segment1);
        return this.listToBalanceXML(list);
    }

    /**
     * @param periodName    期间
     * @param pageNo        页码
     * @param pageSize      页面大小
     * @param username      用户账号
     * @param password      用户密码
     * @return              根据期间查询所有余额(分页方式)
     */
    @Override
    public String getAllBalanceByPeriodName(String periodName, String pageNo, String pageSize, String username, String password) {
        log.info("getAllBalanceByPeriodName():request:{periodName-{},username-{}}", periodName, username);
        if ((username != "" && perCompCode.equals("YDZ") && perUserName.equals(username) && perPasswd.equals(password))
                || sysAppUserService.hasPermit("YDZ", username, password)) {
            perCompCode = "YDZ";
            perUserName = username;
            perPasswd = password;
        } else {
            return sysAppUserService.getErrMsg();
        }
        final int pageNoInt = PageUtil.handlePageNo(pageNo);
        final int pageSizeInt = PageUtil.handlePageSize(pageSize);

        List list = erpAccountDao.getAllBalanceByPeriodName(periodName,pageNoInt,pageSizeInt);
        return this.listToBalanceXML(list, getBalanceCount(periodName), pageNoInt, pageSizeInt);
    }

    /**
     * 获取记录总数
     * @param periodName
     * @return
     */
    private long getBalanceCount(String periodName) {
        return erpAccountDao.getBalanceCount(periodName);
    }

    // 根据科目编码和公司三字码和月份查找科目余额
    public String getBalanceByCombination(Long codeCombinationId,
                                          String segment1, String username, String password) {
        if (!sysAppUserService.hasPermit(segment1, username, password)) {
            return sysAppUserService.getErrMsg();
        }
        List list = erpAccountDao.getBalanceByCombination(codeCombinationId,segment1);
        return this.listToBalanceXML(list);
    }

    /**
     * @param compCode      公司三字码
     * @param beginDate     开始日期
     * @param endDate       结束日期
     * @param username      用户账号
     * @param password      用户密码
     * @return              根据公司三字码、用户名、开始日期,结束日期查询凭证信息
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public String getJournalByDate(final String compCode,
                                   final String beginDate, final String endDate, String username,
                                   String password) {
        if ((username != "" && perCompCode.equals(compCode) && perUserName.equals(username) && perPasswd.equals(password))
                || sysAppUserService.hasPermit(compCode, username, password)) {
            perCompCode = compCode;
            perUserName = username;
            perPasswd = password;
        } else {
            return sysAppUserService.getErrMsg();
        }
        Document root = DocumentHelper.createDocument();
        try {
            List<?> list = erpAccountDao.getJournalByDate(compCode,beginDate,endDate);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date now = sdf.parse(beginDate);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            calendar.add(Calendar.MONTH, 6);
            String[] strbegindate = beginDate.split("-");
            if (Integer.parseInt(strbegindate[1]) > 10) {
                calendar.add(Calendar.YEAR, 1);
            }
            String newbeginDate = sdf.format(calendar.getTime());
            String[] newbeginDates = newbeginDate.split("-");
            newbeginDate = newbeginDates[0] + newbeginDates[1]
                    + newbeginDates[2];


            String[] enddate = endDate.split("-");
            String endDates = enddate[0] + enddate[1] + enddate[2];
            // System.out.println("------------------------------------------->>"+endDates+"---------"+newbeginDate);
            if (Integer.parseInt(endDates) > Integer.parseInt(newbeginDate)) {
                return "beginDate:" + beginDate + "--------endDate:" + endDate;
            }
            return listToJournalXML(list);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return root.asXML();
    }

    /**
     * @param beginDate         开始日期
     * @param endDate           结束日期
     * @param pageNo            页码
     * @param pageSize          页面大小
     * @param username          用户账号
     * @param password          用户密码
     * @return                  根据开始日期, 结束日期查询所有凭证信息(分页方式)
     */
    @Override
    public String getAllJournalByDate(final String beginDate, final String endDate, final String pageNo, final String pageSize, String username, String password) {
        log.info("getAllJournalByDate():request:{beginDate-{},endDate-{},username-{}}", beginDate, endDate, username);
        if ((username != "" && perCompCode.equals("YDZ") && perUserName.equals(username) && perPasswd.equals(password))
                || sysAppUserService.hasPermit("YDZ", username, password)) {
            perCompCode = "YDZ";
            perUserName = username;
            perPasswd = password;
        } else {
            return sysAppUserService.getErrMsg();
        }

        final int pageNoInt = PageUtil.handlePageNo(pageNo);
        final int pageSizeInt = PageUtil.handlePageSize(pageSize);
        List<?> list = null;
        try {
            list = erpAccountDao.getAllJournalByDate(beginDate,endDate,pageNo,pageSize);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return listToJournalXML(list, getJournaltCount(beginDate, endDate), pageNoInt, pageSizeInt);
    }
    //获取记录数
    private long getJournaltCount(String beginDate, String endDate) {
        return erpAccountDao.getJournaltCount(beginDate,endDate);
    }
    /**
     * @param periodName        期间
     * @param pageNo            页码
     * @param pageSize          页面大小
     * @param username          用户账号
     * @param password          用户密码
     * @return                  根据期间查询所有凭证信息(分页方式)
     */
    @Override
    public String getJournalByPeriodName(final String periodName, final String pageNo, final String pageSize, String username, String password) {
        log.info("getJournalByPeriodName():request:{periodName-{},username-{}}", periodName, username);
        if ((username != "" && perCompCode.equals("YDZ") && perUserName.equals(username) && perPasswd.equals(password))
                || sysAppUserService.hasPermit("YDZ", username, password)) {
            perCompCode = "YDZ";
            perUserName = username;
            perPasswd = password;
        } else {
            return sysAppUserService.getErrMsg();
        }
        final int pageNoInt = PageUtil.handlePageNo(pageNo);
        final int pageSizeInt = PageUtil.handlePageSize(pageSize);


        List<?> list = null;
        try {
            list = erpAccountDao.getJournalByPeriodName(periodName,pageNo,pageSize);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return listToJournalXML(list, getJournaltCount(periodName), pageNoInt, pageSizeInt);
    }

    private long getJournaltCount(String periodName) {
        return erpAccountDao.getJournaltCountByPeriodName(periodName);
    }

    // 根据科目号和公司三字码和月份查找科目余额
    public String getBalanceByCombinationandperiodName(Long codeCombinationId,
                                                       String segment1, String periodName, String username, String password) {
        if (!sysAppUserService.hasPermit(segment1, username, password)) {
            return sysAppUserService.getErrMsg();
        }
        List<?> list = erpAccountDao.getBalanceByCombinationandperiodName(codeCombinationId,segment1,periodName);
        return this.listToBalanceXML(list);
    }


    /**
     * @param compCode      公司三字码
     * @param username      用户账号
     * @param password      用户密码
     * @return              根据公司三字码、用户账号、查询前三个月凭证信息
     */

    public String getJournal3Month(String compCode, String username,
                                   String password) {
        if (!sysAppUserService.hasPermit(compCode, username, password)) {
            return sysAppUserService.getErrMsg();
        }
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            dateformat.parse(dateformat.format(new Date()));
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
        }
        Calendar calDate = Calendar.getInstance();
        calDate.setTime(new Date());
        calDate.add(Calendar.MONTH, -3);
        return this.getJournalByDate(compCode,
                dateformat.format(calDate.getTime()),
                dateformat.format(new Date()), username, password);
    }

    /**
     * @param pageNo        页码
     * @param pageSize      页面大小
     * @param username      用户账号
     * @param password      用户密码
     * @return              查询近3月所有凭证信息（分页方式）
     */
    @Override
    public String getAllJournal3Month(String pageNo, String pageSize, String username, String password) {
        log.info("getAllJournal3Month():request:{,username-{}}", username);
        if ((username != "" && perCompCode.equals("YDZ") && perUserName.equals(username) && perPasswd.equals(password))
                || sysAppUserService.hasPermit("YDZ", username, password)) {
            perCompCode = "YDZ";
            perUserName = username;
            perPasswd = password;
        } else {
            return sysAppUserService.getErrMsg();
        }
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            dateformat.parse(dateformat.format(new Date()));
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
        }
        Calendar calDate = Calendar.getInstance();
        calDate.setTime(new Date());
        calDate.add(Calendar.MONTH, -3); //
        return this.getAllJournalByDate(dateformat.format(calDate.getTime()), dateformat.format(new Date()), pageNo, pageSize, username, password);
    }

    @Resource
    private ErpIdsInvVoucherDao erpIdsInvVoucherDao;
    /**
     * @param compCode      公司三字码
     * @param beginDate     开始日期
     * @param endDate       结束日期
     * @param username      用户账号
     * @param password      用户密码
     * @return              根据公司三字码，开始日期,结束日期日期获取ERP回写库存凭证信息
     */
    @Override
    public String getInvVoucherInfo(String compCode, String beginDate,
                                    String endDate, String username, String password) {
        log.info("getInvVoucherInfo():request:{compCode-{},beginDate-{},endDate-{},username-{}}", compCode, beginDate, endDate, username);
        if ((username != "" && perCompCode.equals(compCode) && perUserName.equals(username) && perPasswd.equals(password))
                || sysAppUserService.hasPermit(compCode, username, password)) {
            perCompCode = compCode;
            perUserName = username;
            perPasswd = password;
        } else {
            return sysAppUserService.getErrMsg();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date dateBeginDate = sdf.parse(beginDate);
            Date dateEndDate = sdf.parse(endDate);
            List<ErpIdsInvVoucher> erpIdsInvVoucherList =
                    erpIdsInvVoucherDao.getInvVoucherInfo(compCode, beginDate, endDate);
            if (erpIdsInvVoucherList == null || erpIdsInvVoucherList.size() < 1) {
                return noData("getInvVoucherInfo");
            }
            return listToInvVoucherXML(erpIdsInvVoucherList);
        } catch (Exception e) {
            log.error("getInvVoucherInfo():error-{}", e.getCause());
            return errorMsg("getInvVoucherInfo", e.getMessage());
        }
    }

    @Resource
    private MdsGlFlexValuesDao mdsGlFlexValuesDao;

    static int totalGlFlexValueCount = 0;

    /**
     * @param pageNo        页码
     * @param pageSize      页面大小
     * @param username      用户账号
     * @param password      用户密码
     * @return              查询所有辅助项信息(分页方式)
     */
    @Override
    public String getAllGLFlexValues(String pageNo, String pageSize, String username, String password) {
        log.info("getAllGLFlexValues():request:{,username-{}}", username);
        if ((username != "" && perCompCode.equals("YDZ") && perUserName.equals(username) && perPasswd.equals(password))
                || sysAppUserService.hasPermit("YDZ", username, password)) {
            perCompCode = "YDZ";
            perUserName = username;
            perPasswd = password;
        } else {
            return sysAppUserService.getErrMsg();
        }
        try {
            int pageNoInt = PageUtil.handlePageNo(pageNo);
            int pageSizeInt = PageUtil.handlePageSize(pageSize);


            //查询第一页数据时候初始化总量
            if (pageNoInt == 1) {
                totalGlFlexValueCount = mdsGlFlexValuesDao.getAllMdsGlFlexValuesCount();
            }
            int total = totalGlFlexValueCount <= 0 ? mdsGlFlexValuesDao.getAllMdsGlFlexValuesCount() : totalGlFlexValueCount;


            int startRow = (pageNoInt - 1) * pageSizeInt;
            int endRow = startRow + pageSizeInt;
            List<MdsGlFlexValues> mdsGlFlexValuesList = mdsGlFlexValuesDao.getAllMdsGlFlexValues(startRow, endRow);
            if (mdsGlFlexValuesList == null || mdsGlFlexValuesList.size() < 1) {
                return noData("getAllGLFlexValues");
            }
            return wrapGLFlexValues2XML(mdsGlFlexValuesList, total, pageNoInt, pageSizeInt);
        } catch (Exception e) {
            log.error("getAllGLFlexValues():error-{}", e.getCause());
            return errorMsg("getAllGLFlexValues", e.getMessage());
        }
    }

    static int totalGlFlexValueCount2 = 0;
    /**
     * @param usedComps             使用单位编码
     * @param flexValueSetName      辅助项类型名称
     * @param pageNo                页码
     * @param pageSize              页面大小
     * @param username              用户账号
     * @param password              用户密码
     * @return                      通过使用单位编码和辅助项类型名称查询所有所有辅助项信息(分页方式)
     */
    @Override
    public String getAllGLFlexValuesByUsedCompsAndFlexValueSetName(String usedComps, String flexValueSetName, String pageNo, String pageSize, String username, String password) {
        log.info("getAllGLFlexValuesByUsedCompsAndFlexValueSetName():request:{,usedComps-{},flexValueSetName-{},username-{}}", usedComps, flexValueSetName, username);
        if ((username != "" && perCompCode.equals("YDZ") && perUserName.equals(username) && perPasswd.equals(password))
                || sysAppUserService.hasPermit("YDZ", username, password)) {
            perCompCode = "YDZ";
            perUserName = username;
            perPasswd = password;
        } else {
            return sysAppUserService.getErrMsg();
        }
        if (null == usedComps) {
            log.error("getAllGLFlexValuesByUsedCompsAndFlexValueSetName():error-{usedComps is null}");
            return errorMsg("getAllGLFlexValuesByUsedCompsAndFlexValueSetName", "usedComps is null");
        }
        if (null == flexValueSetName) {
            log.error("getAllGLFlexValuesByUsedCompsAndFlexValueSetName():error-{flexValueSetName is null}");
            return errorMsg("getAllGLFlexValuesByUsedCompsAndFlexValueSetName", "flexValueSetName is null");
        }


        try {
            int pageNoInt = PageUtil.handlePageNo(pageNo);
            int pageSizeInt = PageUtil.handlePageSize(pageSize);


            //查询第一页数据时候初始化总量
            if (pageNoInt == 1) {
                totalGlFlexValueCount2 = mdsGlFlexValuesDao.getAllGLFlexValuesCountByUsedCompsAndFlexValueSetName(usedComps, flexValueSetName);
            }
            int total = totalGlFlexValueCount2 <= 0 ? mdsGlFlexValuesDao.getAllGLFlexValuesCountByUsedCompsAndFlexValueSetName(usedComps, flexValueSetName) : totalGlFlexValueCount2;


            int startRow = (pageNoInt - 1) * pageSizeInt;
            int endRow = startRow + pageSizeInt;
            List<MdsGlFlexValues> mdsGlFlexValuesList = mdsGlFlexValuesDao.getAllGLFlexValuesByUsedCompsAndFlexValueSetName(usedComps, flexValueSetName, startRow, endRow);
            if (mdsGlFlexValuesList == null || mdsGlFlexValuesList.size() < 1) {
                return noData("getAllGLFlexValuesByUsedCompsAndFlexValueSetName");
            }
            return wrapGLFlexValues2XML(mdsGlFlexValuesList, total, pageNoInt, pageSizeInt);
        } catch (Exception e) {
            log.error("getAllGLFlexValuesByUsedCompsAndFlexValueSetName():error-{}", e.getCause());
            return errorMsg("getAllGLFlexValuesByUsedCompsAndFlexValueSetName", e.getMessage());
        }
    }

    @Resource
    private MdsOrganizationVDao mdsOrganizationVDao;

    /**
     * @param username      用户账号
     * @param password      用户密码
     * @return              查询所有业务实体基础信息
     */
    @Override
    public String getAllMdsOrganization(String username, String password) {
        log.info("getAllMdsOrganization():request:{,username-{}}", username);
        if ((username != "" && perCompCode.equals("YDZ") && perUserName.equals(username) && perPasswd.equals(password))
                || sysAppUserService.hasPermit("YDZ", username, password)) {
            perCompCode = "YDZ";
            perUserName = username;
            perPasswd = password;
        } else {
            return sysAppUserService.getErrMsg();
        }
        try {
            List<MdsOrganizationV> mdsOrganizationVList = mdsOrganizationVDao.getAllMdsOrganization();
            if (mdsOrganizationVList == null || mdsOrganizationVList.size() < 1) {
                return noData("getAllMdsOrganization");
            }
            return wrapMdsOrganizationV2XML(mdsOrganizationVList);
        } catch (Exception e) {
            log.error("getAllMdsOrganization():error-{}", e.getCause());
            return errorMsg("getAllMdsOrganization", e.getMessage());
        }
    }

    @Resource
    private MdsHfmEntityDao mdsHfmEntityDao;

    /**
     * @param username      用户账号
     * @param password      用户密码
     * @return              查询所有HFM单位信息
     */
    @Override
    public String getAllMdsHfmEntity(String username, String password) {
        log.info("getAllMdsHfmEntity():request:{,username-{}}", username);
        if ((username != "" && perCompCode.equals("YDZ") && perUserName.equals(username) && perPasswd.equals(password))
                || sysAppUserService.hasPermit("YDZ", username, password)) {
            perCompCode = "YDZ";
            perUserName = username;
            perPasswd = password;
        } else {
            return sysAppUserService.getErrMsg();
        }
        try {
            List<MdsHfmEntity> mdsHfmEntityList = mdsHfmEntityDao.getAllMdsHfmEntity();
            if (mdsHfmEntityList == null || mdsHfmEntityList.size() < 1) {
                return noData("getAllMdsHfmEntity");
            }
            return wrapMdsHfmEntity2XML(mdsHfmEntityList);
        } catch (Exception e) {
            log.error("getAllMdsOrganization():error-{}", e.getCause());
            return errorMsg("getAllMdsOrganization", e.getMessage());
        }
    }

    @Resource
    private MdsFlexValuesDao mdsFlexValuesDao;

    /**
     * @param flexType      段值类型
     * @param compCode      公司三字码
     * @return              根据段值类型，三字码，返回段值信息
     */
    @Override
    public String getMdsFlexValuesByTypeAndCompCode(String flexType, String compCode) {
        log.info("getMdsFlexValuesByTypeAndCompCode():request:{flexType-{},compCode-{}}", flexType, compCode);


        if (isEmpty(trimToEmpty(flexType))) {
            log.error("getMdsFlexValuesByTypeAndCompCode():error-{flex type is null}");
            return errorMsg("getMdsFlexValuesByTypeAndCompCode", "flexType is null");
        }


        if (isEmpty(trimToEmpty(compCode))) {
            log.error("getMdsFlexValuesByTypeAndCompCode():error-{compCode is null}");
            return errorMsg("getMdsFlexValuesByTypeAndCompCode", "compCode is null");
        }


        return wrapMdsFlexValueXML(mdsFlexValuesDao.getMdsFlexValuesByTypeAndCompCode(flexType, compCode));
    }

    /**
     * @param mdsFlexValuesList
     * @return  将段值信息包装成XML
     */
    private String wrapMdsFlexValueXML(List<MdsFlexValues> mdsFlexValuesList) {
        Document root = null;
        root = DocumentHelper.createDocument();
        Element element = root.addElement("service");
        element.addElement("name").setText("段值信息");
        element.addElement("type").setText("发布服务");
        Element datalist = element.addElement("datalist");
        for (int i = 0; i < mdsFlexValuesList.size(); i++) {
            MdsFlexValues mdsFlexValues = mdsFlexValuesList.get(i);
            Element data = datalist.addElement("data");
            data.addElement("flexValue").setText(StringUtil.convertToString(mdsFlexValues.getFlexValue()));
            data.addElement("flexDescription").setText(StringUtil.convertToString(mdsFlexValues.getFlexDescription()));
        }
        return root.asXML();
    }


    @Override
    public String getMdsFlexValuesByTypeAndCompCodeAndDescription(String flexType, String compCode, String flexDescription) {
        log.info("getMdsFlexValuesByTypeAndCompCodeAndDescription():request:{flexType-{},compCode-{},flexDescription-{}}", flexType, compCode, flexDescription);
        if (isEmpty(trimToEmpty(flexType))) {
            log.error("getMdsFlexValuesByTypeAndCompCodeAndDescription():error-{flex type is null}");
            return errorMsg("getMdsFlexValuesByTypeAndCompCodeAndDescription", "flexType is null");
        }
        if (isEmpty(trimToEmpty(compCode))) {
            log.error("getMdsFlexValuesByTypeAndCompCodeAndDescription():error-{compCode is null}");
            return errorMsg("getMdsFlexValuesByTypeAndCompCodeAndDescription", "compCode is null");
        }
        if (isEmpty(trimToEmpty(flexDescription))) {
            log.error("getMdsFlexValuesByTypeAndCompCodeAndDescription():error-{flexDescription is null}");
            return errorMsg("getMdsFlexValuesByTypeAndCompCodeAndDescription", "flexDescription is null");
        }
        return wrapMdsFlexValueXML(mdsFlexValuesDao.getMdsFlexValuesByTypeAndCompCodeAndDescription(flexType, compCode, flexDescription));
    }

    @Override
    public String getJournalByPeriodNameAndJeSourceAndCompCode(final String periodName, final String jeSource, final String compCode, final String pageNo, final String pageSize, String username, String password) {
        log.info("getJournalByPeriodNameAndSourceAndCompCode():request:{periodName-{},jeSource-{},compCode-{},username-{}}", periodName, jeSource, compCode, username);
        if ((username != "" && perCompCode.equals("YDZ") && perUserName.equals(username) && perPasswd.equals(password))
                || sysAppUserService.hasPermit("YDZ", username, password)) {
            perCompCode = "YDZ";
            perUserName = username;
            perPasswd = password;
        } else {
            return sysAppUserService.getErrMsg();
        }


        if (null == periodName) {
            log.error("getJournalByPeriodNameAndJeSourceAndCompCode():error-{periodName is null}");
            return errorMsg("getJournalByPeriodNameAndJeSourceAndCompCode", "periodName is null");
        }
        if (null == jeSource) {
            log.error("getJournalByPeriodNameAndJeSourceAndCompCode():error-{jeSource is null}");
            return errorMsg("getJournalByPeriodNameAndJeSourceAndCompCode", "jeSource is null");
        }
        if (null == compCode) {
            log.error("getJournalByPeriodNameAndJeSourceAndCompCode():error-{compCode is null}");
            return errorMsg("getJournalByPeriodNameAndJeSourceAndCompCode", "compCode is null");
        }


        final int pageNoInt = PageUtil.handlePageNo(pageNo);
        final int pageSizeInt = PageUtil.handlePageSize(pageSize);


        List<?> list = null;
        try {
            list = erpAccountDao.getJournalByPeriodNameAndJeSourceAndCompCode(periodName,jeSource,compCode,pageNoInt,pageSizeInt);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return listToJournalXML(list, getJournaltCount(periodName), pageNoInt, pageSizeInt);
    }

    @Resource
    private MdsEhrErpDeptDao mdsEhrErpDeptDao;


    @Override
    public String getEhrErpDeptByErpCompCode(String erpCompCode, String username, String password) {
        log.info("getEhrErpDeptByErpCompCode():request:{,erpCompCode-{}username-{}}", erpCompCode, username);
        if ((username != "" && perCompCode.equals("YDZ") && perUserName.equals(username) && perPasswd.equals(password))
                || sysAppUserService.hasPermit("YDZ", username, password)) {
            perCompCode = "YDZ";
            perUserName = username;
            perPasswd = password;
        } else {
            return sysAppUserService.getErrMsg();
        }


        if (null == erpCompCode) {
            log.error("getEhrErpDeptByErpCompCode():error-{erpCompCode is null}");
            return errorMsg("getEhrErpDeptByErpCompCode", "erpCompCode is null");
        }


        try {
            List<MdsEhrErpDept> mdsEhrErpDeptList = mdsEhrErpDeptDao.getEhrErpDeptByErpCompCode(erpCompCode);
            if (mdsEhrErpDeptList == null || mdsEhrErpDeptList.size() < 1) {
                return noData("getEhrErpDeptByErpCompCode");
            }
            return wrapMdsEhrErpDeptXML(mdsEhrErpDeptList);
        } catch (Exception e) {
            log.error("getEhrErpDeptByErpCompCode():error-{}", e.getCause());
            return errorMsg("getEhrErpDeptByErpCompCode", e.getMessage());
        }
    }

    private String wrapMdsEhrErpDeptXML(List<MdsEhrErpDept> mdsEhrErpDeptList) {
        Document root = null;
        root = DocumentHelper.createDocument();
        Element element = root.addElement("service");
        element.addElement("name").setText("EHR和EPR映射信息");
        element.addElement("type").setText("发布服务");
        Element datalist = element.addElement("datalist");
        for (int i = 0; i < mdsEhrErpDeptList.size(); i++) {
            MdsEhrErpDept mdsEhrErpDept = mdsEhrErpDeptList.get(i);
            Element data = datalist.addElement("data");
            data.addElement("erpCompCode").setText(StringUtil.convertToString(mdsEhrErpDept.getErpCompCode()));
            data.addElement("erpCompName").setText(StringUtil.convertToString(mdsEhrErpDept.getErpCompName()));
            data.addElement("ehrCompCode").setText(StringUtil.convertToString(mdsEhrErpDept.getEhrCompCode()));
            data.addElement("ehrDeptCode").setText(StringUtil.convertToString(mdsEhrErpDept.getEhrDeptCode()));
            data.addElement("ehrDeptName").setText(StringUtil.convertToString(mdsEhrErpDept.getEhrDeptName()));
            data.addElement("erpDeptCode").setText(StringUtil.convertToString(mdsEhrErpDept.getErpDeptCode()));
            data.addElement("erpDeptName").setText(StringUtil.convertToString(mdsEhrErpDept.getErpDeptName()));
            data.addElement("attribute1").setText(StringUtil.convertToString(mdsEhrErpDept.getAttribute1()));
            data.addElement("attribute2").setText(StringUtil.convertToString(mdsEhrErpDept.getAttribute2()));
            data.addElement("attribute3").setText(StringUtil.convertToString(mdsEhrErpDept.getAttribute3()));
            data.addElement("attribute4").setText(StringUtil.convertToString(mdsEhrErpDept.getAttribute4()));
            data.addElement("attribute5").setText(StringUtil.convertToString(mdsEhrErpDept.getAttribute5()));
            data.addElement("attribute6").setText(StringUtil.convertToString(mdsEhrErpDept.getAttribute6()));
            data.addElement("attribute7").setText(StringUtil.convertToString(mdsEhrErpDept.getAttribute7()));
            data.addElement("attribute8").setText(StringUtil.convertToString(mdsEhrErpDept.getAttribute8()));
            data.addElement("attribute9").setText(StringUtil.convertToString(mdsEhrErpDept.getAttribute9()));
            data.addElement("attribute10").setText(StringUtil.convertToString(mdsEhrErpDept.getAttribute10()));
        }
        return root.asXML();
    }

    /**
     * 合并报表实体及层级
     * @param mdsHfmEntityList
     * @return
     */
    private String wrapMdsHfmEntity2XML(List<MdsHfmEntity> mdsHfmEntityList) {
        Document root = null;
        root = DocumentHelper.createDocument();
        Element element = root.addElement("service");
        element.addElement("name").setText("HFM单位信息");
        element.addElement("type").setText("发布服务");
        Element datalist = element.addElement("datalist");
        for (int i = 0; i < mdsHfmEntityList.size(); i++) {
            MdsHfmEntity mdsHfmEntity = mdsHfmEntityList.get(i);
            Element data = datalist.addElement("data");
            data.addElement("id").setText(StringUtil.convertToString(mdsHfmEntity.getId()));
            data.addElement("label").setText(StringUtil.convertToString(mdsHfmEntity.getLabel()));
            data.addElement("parentId").setText(StringUtil.convertToString(mdsHfmEntity.getParentId()));
            data.addElement("parentlabel").setText(StringUtil.convertToString(mdsHfmEntity.getParentlabel()));
            data.addElement("description").setText(StringUtil.convertToString(mdsHfmEntity.getDescription()));
            data.addElement("isleaf").setText(StringUtil.convertToString(mdsHfmEntity.getIsleaf()));
        }
        return root.asXML();


    }

    /**
     * 将辅助项信息包装成XML
     * @param mdsOrganizationVList
     * @return
     */
    private String wrapMdsOrganizationV2XML(List<MdsOrganizationV> mdsOrganizationVList) {
        Document root = null;
        root = DocumentHelper.createDocument();
        Element element = root.addElement("service");
        element.addElement("name").setText("业务实体基础信息");
        element.addElement("type").setText("发布服务");
        Element datalist = element.addElement("datalist");
        for (int i = 0; i < mdsOrganizationVList.size(); i++) {
            MdsOrganizationV mdsOrganizationV = mdsOrganizationVList.get(i);
            Element data = datalist.addElement("data");
            data.addElement("sobId").setText(StringUtil.convertToString(mdsOrganizationV.getSobId()));
            data.addElement("sobName").setText(StringUtil.convertToString(mdsOrganizationV.getSobName()));
            data.addElement("organizationId").setText(StringUtil.convertToString(mdsOrganizationV.getOrganizationId()));
            data.addElement("acctCompCode").setText(StringUtil.convertToString(mdsOrganizationV.getAcctCompCode()));
            data.addElement("acctCompName").setText(StringUtil.convertToString(mdsOrganizationV.getAcctCompName()));
            data.addElement("compCode").setText(StringUtil.convertToString(mdsOrganizationV.getCompCode()));
            data.addElement("compName").setText(StringUtil.convertToString(mdsOrganizationV.getCompName()));
            data.addElement("compSeq").setText(StringUtil.convertToString(mdsOrganizationV.getCompSeq()));
            data.addElement("ehrCompCode").setText(StringUtil.convertToString(mdsOrganizationV.getEhrCompCode()));
            data.addElement("hfmComCode").setText(StringUtil.convertToString(mdsOrganizationV.getHfmCompCode()));
            data.addElement("effectiveDate").setText(StringUtil.date2String(mdsOrganizationV.getEffectiveDate()));
            data.addElement("invalidDate").setText(StringUtil.date2String(mdsOrganizationV.getInvalidDate()));
        }
        return root.asXML();


    }

    private String wrapGLFlexValues2XML(List<MdsGlFlexValues> mdsGlFlexValuesList, int total, int pageNo, int pageSize) {
        Document root = null;
        root = DocumentHelper.createDocument();
        Element element = root.addElement("service");
        element.addElement("name").setText("辅助项信息");
        element.addElement("type").setText("发布服务");
        element.addElement("total").setText(StringUtil.convertToString(total));
        element.addElement("pageNo").setText(StringUtil.convertToString(pageNo));
        element.addElement("pageSize").setText(StringUtil.convertToString(pageSize));
        Element datalist = element.addElement("datalist");
        for (int i = 0; i < mdsGlFlexValuesList.size(); i++) {
            MdsGlFlexValues mdsGlFlexValues = mdsGlFlexValuesList.get(i);
            Element data = datalist.addElement("data");
            data.addElement("flexValueSetID").setText(StringUtil.convertToString(mdsGlFlexValues.getFlexValueSetId()));
            data.addElement("flexValueSetName").setText(StringUtil.convertToString(mdsGlFlexValues.getFlexValueSetName()));
            data.addElement("flexValueID").setText(StringUtil.convertToString(mdsGlFlexValues.getFlexValueId()));
            data.addElement("flexValue").setText(StringUtil.convertToString(mdsGlFlexValues.getFlexValue()));
            data.addElement("flexValueMeaning").setText(StringUtil.convertToString(mdsGlFlexValues.getFlexValueMeaning()));
            data.addElement("description").setText(StringUtil.convertToString(mdsGlFlexValues.getDescription()));
            data.addElement("hierarchyLevel").setText(StringUtil.convertToString(mdsGlFlexValues.getHierarchyLevel()));
            data.addElement("enabledFlag").setText(StringUtil.convertToString(mdsGlFlexValues.getEnabledFlag()));
            data.addElement("summaryFlag").setText(StringUtil.convertToString(mdsGlFlexValues.getSummaryFlag()));
            data.addElement("startDateActive").setText(StringUtil.date2String(mdsGlFlexValues.getStartDateActive()));
            data.addElement("endDateActive").setText(StringUtil.date2String(mdsGlFlexValues.getEndDateActive()));
            data.addElement("usedComps").setText(StringUtil.convertToString(mdsGlFlexValues.getUsedComps()));
        }
        return root.asXML();


    }

    /**
     * 返回空数据的时候的信息
     * @param serviceName
     * @return
     */
    private String noData(String serviceName) {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><service><name>" + serviceName + "</name><type>发布服务</type><datalist><!--查无数据--></datalist></service>";
    }

    /**
     * 将查询出的Erp回写库存凭证list转换成xml字符串
     * @param list
     * @return
     */
    @SuppressWarnings("rawtypes")
    private String listToInvVoucherXML(List list) {
        Document root = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        root = DocumentHelper.createDocument();
        Element element = root.addElement("service");
        element.addElement("name").setText("ERP回写库存凭证信息");
        element.addElement("type").setText("发布服务");
        Element datalist = element.addElement("datalist");
        for (int i = 0; i < list.size(); i++) {
            ErpIdsInvVoucher obj = (ErpIdsInvVoucher) list.get(i);
            Element data = datalist.addElement("data");
            data.addElement("controlId").setText(StringUtil.convertToString(obj.getControlId()));
            data.addElement("compCode").setText(StringUtil.convertToString(obj.getCompCode()));
            data.addElement("trxId").setText(StringUtil.convertToString(obj.getTrxId()));
            data.addElement("trxType").setText(StringUtil.convertToString(obj.getTrxType()));
            data.addElement("trxDate").setText(sdf.format(obj.getTrxDate()));
            data.addElement("trxAmount").setText(StringUtil.convertToString(obj.getTrxAmount()));
            data.addElement("voucherNum").setText(StringUtil.convertToString(obj.getVoucherNum()));
        }
        return root.asXML();
    }


    /**
     * 返回查询出错信息
     * @param serviceName
     * @param msg
     * @return
     */
    private String errorMsg(String serviceName, String msg) {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><service><name>" + serviceName + "</name><type>发布服务</type><datalist><!--error Message:" + msg + "--></datalist></service>";
    }

    /**
     * 将查询出的list转换成xml字符串
     * @param list
     * @param total
     * @param pageNo
     * @param pageSize
     * @return
     */

    @SuppressWarnings("rawtypes")
    private String listToJournalXML(List list, long total, int pageNo, int pageSize) {
        Document root = null;
        try {
            root = DocumentHelper.createDocument();
            Element element = root.addElement("service");
            element.addElement("name").setText("凭证信息");
            element.addElement("type").setText("发布服务");
            element.addElement("total").setText(StringUtil.convertToString(total));
            element.addElement("pageNo").setText(StringUtil.convertToString(pageNo));
            element.addElement("pageSize").setText(StringUtil.convertToString(pageSize));
            Element datalist = element.addElement("datalist");
            ;
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                   // Object[] obj = (Object[]) list.get(i);
                    MdsJeCertificate certificate = (MdsJeCertificate) list.get(i);
                    Element data = datalist.addElement("data");
                    data.addElement("compCode").setText(StringUtil.convertToString(certificate.getCompCode()));
                    data.addElement("jeHeaderId").setText(StringUtil.convertToString(certificate.getJeHeaderId()));
                    data.addElement("headerName").setText(StringUtil.convertToString(certificate.getHeaderName()));
                    data.addElement("jeCategory").setText(StringUtil.convertToString(certificate.getJeCategory()));
                    data.addElement("userJeCategoryName").setText(StringUtil.convertToString(certificate.getUserJeCategoryName()));
                    data.addElement("jeSource").setText(StringUtil.convertToString(certificate.getJeSource()));
                    data.addElement("userJeSourceName").setText(StringUtil.convertToString(certificate.getUserJeSourceName()));
                    data.addElement("periodYear").setText(StringUtil.convertToString(certificate.getPeriodYear()));
                    data.addElement("dateCreated").setText(StringUtil.convertToString(certificate.getDateCreated()));
                    data.addElement("periodName").setText(StringUtil.convertToString(certificate.getHeaderName()));
                    data.addElement("headerDesc").setText(StringUtil.convertToString(certificate.getHeaderDesc()));
                    data.addElement("docSequenceValue").setText(StringUtil.convertToString(certificate.getDocSequenceValue()));
                    data.addElement("currencyCode").setText(StringUtil.convertToString(certificate.getCurrencyCode()));
                    data.addElement("defaultEffectiveDate").setText(StringUtil.convertToString(certificate.getDefaultEffectiveDate()));
                    data.addElement("jeLineNum").setText(StringUtil.convertToString(certificate.getJeLineNum()));
                    data.addElement("lineDesc").setText(StringUtil.convertToString(certificate.getLineDesc()));
                    data.addElement("codeCombinationId").setText(StringUtil.convertToString(certificate.getCodeCombinationId()));
                    data.addElement("accountedDr").setText(StringUtil.convertToString(certificate.getAccountedDr()));
                    data.addElement("accountedCr").setText(StringUtil.convertToString(certificate.getAccountedCr()));
                    data.addElement("ledgerCoaId").setText(StringUtil.convertToString(certificate.getLedgerCoaId()));


                    data.addElement("currencyConversionRate").setText(StringUtil.convertToString(certificate.getCurrencyConversionRate()));
                    data.addElement("currencyConversionType").setText(StringUtil.convertToString(certificate.getCurrencyConversionType()));
                    data.addElement("maker").setText(StringUtil.convertToString(certificate.getMaker()));
                    data.addElement("approver").setText(StringUtil.convertToString(certificate.getApprover()));


                    data.addElement("attribute1").setText(StringUtil.convertToString(certificate.getAttribute1()));
                    data.addElement("attribute2").setText(StringUtil.convertToString(certificate.getAttribute2()));
                    data.addElement("attribute3").setText(StringUtil.convertToString(certificate.getAttribute3()));
                    data.addElement("attribute4").setText(StringUtil.convertToString(certificate.getAttribute4()));
                    data.addElement("attribute5").setText(StringUtil.convertToString(certificate.getAttribute5()));
                    data.addElement("attribute6").setText(StringUtil.convertToString(certificate.getAttribute6()));
                    data.addElement("attribute7").setText(StringUtil.convertToString(certificate.getAttribute7()));
                    data.addElement("attribute8").setText(StringUtil.convertToString(certificate.getAttribute8()));
                    data.addElement("attribute9").setText(StringUtil.convertToString(certificate.getAttribute9()));
                    data.addElement("attribute10").setText(StringUtil.convertToString(certificate.getAttribute10()));
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return root.asXML();
    }

    @SuppressWarnings("rawtypes")
    private String listToJournalXML(List list) {
        Document root = null;
        try {
            root = DocumentHelper.createDocument();
            Element element = root.addElement("service");
            element.addElement("name").setText("凭证信息");
            element.addElement("type").setText("发布服务");
            Element datalist = element.addElement("datalist");
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    //Object[] obj = (Object[]) list.get(i);
                    MdsJeCertificate certificate = (MdsJeCertificate) list.get(i);
                    Element data = datalist.addElement("data");
                    data.addElement("compCode").setText(StringUtil.convertToString(certificate.getCompCode()));
                    data.addElement("jeHeaderId").setText(StringUtil.convertToString(certificate.getJeHeaderId()));
                    data.addElement("headerName").setText(StringUtil.convertToString(certificate.getHeaderName()));
                    data.addElement("jeCategory").setText(StringUtil.convertToString(certificate.getJeCategory()));
                    data.addElement("userJeCategoryName").setText(StringUtil.convertToString(certificate.getUserJeCategoryName()));
                    data.addElement("jeSource").setText(StringUtil.convertToString(certificate.getJeSource()));
                    data.addElement("userJeSourceName").setText(StringUtil.convertToString(certificate.getUserJeSourceName()));
                    data.addElement("periodYear").setText(StringUtil.convertToString(certificate.getPeriodYear()));
                    data.addElement("dateCreated").setText(StringUtil.convertToString(certificate.getDateCreated()));
                    data.addElement("periodName").setText(StringUtil.convertToString(certificate.getPeriodName()));
                    data.addElement("headerDesc").setText(StringUtil.convertToString(certificate.getHeaderDesc()));
                    data.addElement("docSequenceValue").setText(StringUtil.convertToString(certificate.getDocSequenceValue()));
                    data.addElement("currencyCode").setText(StringUtil.convertToString(certificate.getCurrencyCode()));
                    data.addElement("defaultEffectiveDate").setText(StringUtil.convertToString(certificate.getDefaultEffectiveDate()));
                    data.addElement("jeLineNum").setText(StringUtil.convertToString(certificate.getJeLineNum()));
                    data.addElement("lineDesc").setText(StringUtil.convertToString(certificate.getLineDesc()));
                    data.addElement("codeCombinationId").setText(StringUtil.convertToString(certificate.getCodeCombinationId()));
                    data.addElement("accountedDr").setText(StringUtil.convertToString(certificate.getAccountedDr()));
                    data.addElement("accountedCr").setText(StringUtil.convertToString(certificate.getAccountedCr()));
                    data.addElement("ledgerCoaId").setText(StringUtil.convertToString(certificate.getLedgerCoaId()));
                    data.addElement("attribute1").setText(StringUtil.convertToString(certificate.getAttribute1()));
                    data.addElement("attribute2").setText(StringUtil.convertToString(certificate.getAttribute2()));
                    data.addElement("attribute3").setText(StringUtil.convertToString(certificate.getAttribute3()));
                    data.addElement("attribute4").setText(StringUtil.convertToString(certificate.getAttribute4()));
                    data.addElement("attribute5").setText(StringUtil.convertToString(certificate.getAttribute5()));
                    data.addElement("attribute6").setText(StringUtil.convertToString(certificate.getAttribute6()));
                    data.addElement("attribute7").setText(StringUtil.convertToString(certificate.getAttribute7()));
                    data.addElement("attribute8").setText(StringUtil.convertToString(certificate.getAttribute8()));
                    data.addElement("attribute9").setText(StringUtil.convertToString(certificate.getAttribute9()));
                    data.addElement("attribute10").setText(StringUtil.convertToString(certificate.getAttribute10()));
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return root.asXML();
    }

    /**
     * 将查询出的list转换成xml字符串
     * @param list
     * @return
     */
    @SuppressWarnings("rawtypes")
    private String listToAccountCombinationsXML(List list) {
        Document root = null;
        try {
            root = DocumentHelper.createDocument();
            Element element = root.addElement("service");
            element.addElement("name").setText("科目体系信息");
            element.addElement("type").setText("发布服务");
            Element datalist = element.addElement("datalist");
            for (int i = 0; i < list.size(); i++) {
                MdsAccountCombinations accountCombinations = (MdsAccountCombinations) list.get(i);
                Element data = datalist.addElement("data");
                data.addElement("sobId").setText(StringUtil.convertToString(accountCombinations.getCodeCombinationId()));
                data.addElement("sobName").setText(accountCombinations.getSobName() == null ? "" : accountCombinations.getSobName());
                data.addElement("chartOfAccountsId").setText(StringUtil.convertToString(accountCombinations.getChartOfAccountsId()));
                data.addElement("codeCombinationId").setText(StringUtil.convertToString(accountCombinations.getCodeCombinationId()));
                data.addElement("orgName").setText(StringUtil.convertToString(accountCombinations.getOrgName()));
                data.addElement("concatenatedSegments").setText(StringUtil.convertToString(accountCombinations.getConcatenatedSegments()));
                data.addElement("gccDesc").setText(StringUtil.convertToString(accountCombinations.getGccDesc()));
                data.addElement("segment1").setText(StringUtil.convertToString(accountCombinations.getSegment1()));
                data.addElement("accCom").setText(StringUtil.convertToString(accountCombinations.getAccCom()));
                data.addElement("segment2").setText(StringUtil.convertToString(accountCombinations.getSegment2()));
                data.addElement("accCc").setText(StringUtil.convertToString(accountCombinations.getAccCc()));
                data.addElement("segment3").setText(StringUtil.convertToString(accountCombinations.getSegment3()));
                data.addElement("accDesc").setText(StringUtil.convertToString(accountCombinations.getAccDesc()));
                data.addElement("segment4").setText(StringUtil.convertToString(accountCombinations.getSegment4()));
                data.addElement("accSub").setText(StringUtil.convertToString(accountCombinations.getAccSub()));
                data.addElement("segment5").setText(StringUtil.convertToString(accountCombinations.getSegment5()));
                data.addElement("accInt").setText(StringUtil.convertToString(accountCombinations.getAccInt()));
                data.addElement("segment6").setText(StringUtil.convertToString(accountCombinations.getSegment6()));
                data.addElement("accPj").setText(StringUtil.convertToString(accountCombinations.getAccPj()));
                data.addElement("segment7").setText(StringUtil.convertToString(accountCombinations.getSegment7()));
                data.addElement("accProd").setText(StringUtil.convertToString(accountCombinations.getAccProd()));
                data.addElement("segment8").setText(StringUtil.convertToString(accountCombinations.getSegment8()));
                data.addElement("accEntity").setText(StringUtil.convertToString(accountCombinations.getAccEntity()));
                data.addElement("segment9").setText(StringUtil.convertToString(accountCombinations.getSegment9()));
                data.addElement("accSpare1").setText(StringUtil.convertToString(accountCombinations.getAccSpare1()));
                data.addElement("segment10").setText(StringUtil.convertToString(accountCombinations.getSegment10()));
                data.addElement("accSpare2").setText(StringUtil.convertToString(accountCombinations.getAccSpare2()));
                data.addElement("accountType").setText(StringUtil.convertToString(accountCombinations.getAccountType()));
                data.addElement("accountDrCr").setText(StringUtil.convertToString(accountCombinations.getAccountDrCr()));
                data.addElement("accountTypeDesc").setText(StringUtil.convertToString(accountCombinations.getAccountTypeDesc()));
                data.addElement("sourceApplCode").setText(StringUtil.convertToString(accountCombinations.getSourceApplCode()));


            }
            OutputFormat format = OutputFormat.createPrettyPrint(); // 设置XML文档输出格式
            // format.setEncoding("GB2312"); //设置XML文档的编码类型
            format.setSuppressDeclaration(true);
            format.setIndent(true); // 设置是否缩进
            format.setIndent("   "); // 以空格方式实现缩进
            format.setNewlines(true); // 设置是否换行


        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return root.asXML();
    }

    @SuppressWarnings("rawtypes")
    private String listToAccountCombinationsXML(List list, long total, int pageNo, int pageSize) {
        Document root = null;
        try {
            root = DocumentHelper.createDocument();
            Element element = root.addElement("service");
            element.addElement("name").setText("科目体系信息");
            element.addElement("type").setText("发布服务");
            element.addElement("total").setText(StringUtil.convertToString(total));
            element.addElement("pageNo").setText(StringUtil.convertToString(pageNo));
            element.addElement("pageSize").setText(StringUtil.convertToString(pageSize));
            Element datalist = element.addElement("datalist");
            for (int i = 0; i < list.size(); i++) {
                MdsAccountCombinations accountCombinations = (MdsAccountCombinations) list.get(i);
                Element data = datalist.addElement("data");
                data.addElement("sobId").setText(StringUtil.convertToString(accountCombinations.getCodeCombinationId()));
                data.addElement("sobName").setText(accountCombinations.getSobName() == null ? "" : accountCombinations.getSobName());
                data.addElement("chartOfAccountsId").setText(StringUtil.convertToString(accountCombinations.getChartOfAccountsId()));
                data.addElement("codeCombinationId").setText(StringUtil.convertToString(accountCombinations.getCodeCombinationId()));
                data.addElement("orgName").setText(StringUtil.convertToString(accountCombinations.getOrgName()));
                data.addElement("concatenatedSegments").setText(StringUtil.convertToString(accountCombinations.getConcatenatedSegments()));
                data.addElement("gccDesc").setText(StringUtil.convertToString(accountCombinations.getGccDesc()));
                data.addElement("segment1").setText(StringUtil.convertToString(accountCombinations.getSegment1()));
                data.addElement("accCom").setText(StringUtil.convertToString(accountCombinations.getAccCom()));
                data.addElement("segment2").setText(StringUtil.convertToString(accountCombinations.getSegment2()));
                data.addElement("accCc").setText(StringUtil.convertToString(accountCombinations.getAccCc()));
                data.addElement("segment3").setText(StringUtil.convertToString(accountCombinations.getSegment3()));
                data.addElement("accDesc").setText(StringUtil.convertToString(accountCombinations.getAccDesc()));
                data.addElement("segment4").setText(StringUtil.convertToString(accountCombinations.getSegment4()));
                data.addElement("accSub").setText(StringUtil.convertToString(accountCombinations.getAccSub()));
                data.addElement("segment5").setText(StringUtil.convertToString(accountCombinations.getSegment5()));
                data.addElement("accInt").setText(StringUtil.convertToString(accountCombinations.getAccInt()));
                data.addElement("segment6").setText(StringUtil.convertToString(accountCombinations.getSegment6()));
                data.addElement("accPj").setText(StringUtil.convertToString(accountCombinations.getAccPj()));
                data.addElement("segment7").setText(StringUtil.convertToString(accountCombinations.getSegment7()));
                data.addElement("accProd").setText(StringUtil.convertToString(accountCombinations.getAccProd()));
                data.addElement("segment8").setText(StringUtil.convertToString(accountCombinations.getSegment8()));
                data.addElement("accEntity").setText(StringUtil.convertToString(accountCombinations.getAccEntity()));
                data.addElement("segment9").setText(StringUtil.convertToString(accountCombinations.getSegment9()));
                data.addElement("accSpare1").setText(StringUtil.convertToString(accountCombinations.getAccSpare1()));
                data.addElement("segment10").setText(StringUtil.convertToString(accountCombinations.getSegment10()));
                data.addElement("accSpare2").setText(StringUtil.convertToString(accountCombinations.getAccSpare2()));
                data.addElement("accountType").setText(StringUtil.convertToString(accountCombinations.getAccountType()));
                data.addElement("accountDrCr").setText(StringUtil.convertToString(accountCombinations.getAccountDrCr()));
                data.addElement("accountTypeDesc").setText(StringUtil.convertToString(accountCombinations.getAccountTypeDesc()));
                data.addElement("sourceApplCode").setText(StringUtil.convertToString(accountCombinations.getSourceApplCode()));


            }
            OutputFormat format = OutputFormat.createPrettyPrint(); // 设置XML文档输出格式
            // format.setEncoding("GB2312"); //设置XML文档的编码类型
            format.setSuppressDeclaration(true);
            format.setIndent(true); // 设置是否缩进
            format.setIndent("   "); // 以空格方式实现缩进
            format.setNewlines(true); // 设置是否换行


        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return root.asXML();
    }
    /**
     * 将查询出的list转换成xml字符串
     * @param list
     * @return
     */
    @SuppressWarnings("rawtypes")
    private String listToAccountXML(List list) {
        Document root = null;
        try {
            root = DocumentHelper.createDocument();
            Element element = root.addElement("service");
            element.addElement("name").setText("科目信息");
            element.addElement("type").setText("发布服务");
            Element datalist = element.addElement("datalist");
            for (int i = 0; i < list.size(); i++) {
                MdsAccount account = (MdsAccount) list.get(i);
                Element data = datalist.addElement("data");
                data.addElement("acctCode").setText(StringUtil.convertToString(account.getAcctCode()));
                data.addElement("acctName").setText(StringUtil.convertToString(account.getAcctName()));
                data.addElement("acctType").setText(StringUtil.convertToString(account.getAcctType()));
                data.addElement("sourceApplCode").setText(StringUtil.convertToString(account.getSourceApplCode()));
                data.addElement("accountTypeDesc").setText(StringUtil.convertToString(account.getAccountTypeDesc()));
                data.addElement("accountDrCr").setText(StringUtil.convertToString(account.getAccountDrCr()));
                data.addElement("summaryFlag").setText(StringUtil.convertToString(account.getSummaryFlag()));
                data.addElement("hierarchyLevel").setText(StringUtil.convertToString(account.getHierarchyLevel()));
                data.addElement("parentAcctCode").setText(StringUtil.convertToString(account.getPartentAcctCode()));
                data.addElement("enabledFlag").setText(StringUtil.convertToString(account.getEnabledFlag()));
                data.addElement("startDate").setText(StringUtil.date2String(account.getStartDateActive()));
                data.addElement("endDate").setText(StringUtil.date2String(account.getEndDateActive()));
            }
            OutputFormat format = OutputFormat.createPrettyPrint(); // 设置XML文档输出格式
            // format.setEncoding("GB2312"); //设置XML文档的编码类型
            format.setSuppressDeclaration(true);
            format.setIndent(true); // 设置是否缩进
            format.setIndent("   "); // 以空格方式实现缩进
            format.setNewlines(true); // 设置是否换行


        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return root.asXML();
    }
    /**
     * 将查询出的list转换成xml字符串
     * @param list
     * @return
     */


    @SuppressWarnings("rawtypes")
    private String listToAccountSubXML(List list) {
        Document root = null;
        try {
            root = DocumentHelper.createDocument();
            Element element = root.addElement("service");
            element.addElement("name").setText("子科目信息");
            element.addElement("type").setText("发布服务");
            Element datalist = element.addElement("datalist");
            for (int i = 0; i < list.size(); i++) {
                MdsAccountSub accountSub = (MdsAccountSub) list.get(i);
                Element data = datalist.addElement("data");
                data.addElement("acctCodeSub").setText(StringUtil.convertToString(accountSub.getAcctCodeSub()));
                data.addElement("acctName").setText(StringUtil.convertToString(accountSub.getAcctName()));
                data.addElement("sourceApplCode").setText(StringUtil.convertToString(accountSub.getSourceApplCode()));
                data.addElement("accountTypeDesc").setText(StringUtil.convertToString(accountSub.getAccountTypeDesc()));
                data.addElement("accountDrCr").setText(StringUtil.convertToString(accountSub.getAccountDrCr()));
                data.addElement("enabledFlag").setText(StringUtil.convertToString(accountSub.getEnabledFlag()));
                data.addElement("summaryFlag").setText(StringUtil.convertToString(accountSub.getSummaryFlag()));
                data.addElement("ledgerId").setText(StringUtil.convertToString(accountSub.getLedgerId()));
                data.addElement("ledgerDescription").setText(StringUtil.convertToString(accountSub.getLedgerDescription()));
                data.addElement("compSeq").setText(StringUtil.convertToString(accountSub.getCompSeq()));
                data.addElement("ledgerCoaId").setText(StringUtil.convertToString(accountSub.getLedgerCoaId()));
                data.addElement("orgId").setText(StringUtil.convertToString(accountSub.getOrgId()));
                data.addElement("compCode").setText(StringUtil.convertToString(accountSub.getCompCode()));
                data.addElement("orgName").setText(StringUtil.convertToString(accountSub.getOrgName()));
            }
            OutputFormat format = OutputFormat.createPrettyPrint(); // 设置XML文档输出格式
            format.setSuppressDeclaration(true);
            format.setIndent(true); // 设置是否缩进
            format.setIndent("   "); // 以空格方式实现缩进
            format.setNewlines(true); // 设置是否换行
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return root.asXML();
    }


    /**
     * 将查询出的list转换成xml字符串
     * @param list
     * @param total
     * @param pageNo
     * @param pageSize
     * @return
     */
    @SuppressWarnings("rawtypes")
    private String listToAccountSubXML(List list, Long total, int pageNo, int pageSize) {
        Document root = null;
        try {
            root = DocumentHelper.createDocument();
            Element element = root.addElement("service");
            element.addElement("name").setText("子科目信息");
            element.addElement("type").setText("发布服务");
            element.addElement("total").setText(StringUtil.convertToString(total));
            element.addElement("pageNo").setText(StringUtil.convertToString(pageNo));
            element.addElement("pageSize").setText(StringUtil.convertToString(pageSize));
            Element datalist = element.addElement("datalist");
            for (int i = 0; i < list.size(); i++) {
                MdsAccountSub accountSub = (MdsAccountSub) list.get(i);
                Element data = datalist.addElement("data");
                data.addElement("acctCodeSub").setText(StringUtil.convertToString(accountSub.getAcctCodeSub()));
                data.addElement("acctName").setText(StringUtil.convertToString(accountSub.getAcctName()));
                data.addElement("sourceApplCode").setText(StringUtil.convertToString(accountSub.getSourceApplCode()));
                data.addElement("accountTypeDesc").setText(StringUtil.convertToString(accountSub.getAccountTypeDesc()));
                data.addElement("accountDrCr").setText(StringUtil.convertToString(accountSub.getAccountDrCr()));
                data.addElement("enabledFlag").setText(StringUtil.convertToString(accountSub.getEnabledFlag()));
                data.addElement("summaryFlag").setText(StringUtil.convertToString(accountSub.getSummaryFlag()));
                data.addElement("ledgerId").setText(StringUtil.convertToString(accountSub.getLedgerId()));
                data.addElement("ledgerDescription").setText(StringUtil.convertToString(accountSub.getLedgerDescription()));
                data.addElement("compSeq").setText(StringUtil.convertToString(accountSub.getCompSeq()));
                data.addElement("ledgerCoaId").setText(StringUtil.convertToString(accountSub.getLedgerCoaId()));
                data.addElement("orgId").setText(StringUtil.convertToString(accountSub.getOrgId()));
                data.addElement("compCode").setText(StringUtil.convertToString(accountSub.getCompCode()));
                data.addElement("orgName").setText(StringUtil.convertToString(accountSub.getOrgName()));
            }
            OutputFormat format = OutputFormat.createPrettyPrint(); // 设置XML文档输出格式
            format.setSuppressDeclaration(true);
            format.setIndent(true); // 设置是否缩进
            format.setIndent("   "); // 以空格方式实现缩进
            format.setNewlines(true); // 设置是否换行


        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return root.asXML();
    }

    /**
     * 将查询出的余额list转换成xml字符串
     * @param list
     * @return
     */
    @SuppressWarnings("rawtypes")
    private String listToBalanceXML(List list) {
        Document root = null;
        root = DocumentHelper.createDocument();
        Element element = root.addElement("service");
        element.addElement("name").setText("余额查询");
        element.addElement("type").setText("发布服务");
        Element datalist = element.addElement("datalist");
        for (int i = 0; i < list.size(); i++) {
            //Object[] obj = (Object[]) list.get(i);
            AccountBalances accountBalances = (AccountBalances) list.get(i);
            Element data = datalist.addElement("data");
            data.addElement("codeCombinationId").setText(StringUtil.convertToString(accountBalances.getCodeCombinationId()));
            data.addElement("currencyCode").setText(StringUtil.convertToString(accountBalances.getCurrencyCode()));
            data.addElement("periodName").setText(StringUtil.convertToString(accountBalances.getPeriodName()));
            data.addElement("periodType").setText(StringUtil.convertToString(accountBalances.getPeriodType()));
            data.addElement("periodNetDr").setText(StringUtil.convertToString(accountBalances.getPeriodNetDr()));
            data.addElement("periodNetCr").setText(StringUtil.convertToString(accountBalances.getPeriodNetCr()));
            data.addElement("beginBalanceDr").setText(StringUtil.convertToString(accountBalances.getBeginBalanceDr()));
            data.addElement("beginBalanceCr").setText(StringUtil.convertToString(accountBalances.getBeginBalanceCr()));
            data.addElement("endBalance").setText(StringUtil.convertToString(accountBalances.getEndBalance()));


            data.addElement("chartOfAccountsId").setText(StringUtil.convertToString(accountBalances.getChartOfAccountsId()));
            data.addElement("orgName").setText(StringUtil.convertToString(accountBalances.getOrgName()));
            data.addElement("concatenatedSegments").setText(StringUtil.convertToString(accountBalances.getConcatenatedSegments()));
            data.addElement("gccDesc").setText(StringUtil.convertToString(accountBalances.getGccDesc()));
            data.addElement("segment1").setText(StringUtil.convertToString(accountBalances.getSegment1()));
            data.addElement("accCom").setText(StringUtil.convertToString(accountBalances.getAccCom()));
        }
        return root.asXML();
    }

    /**
     * 将查询出的余额list转换成xml字符串
     * @param list
     * @param total
     * @param pageNo
     * @param pageSize
     * @return
     */
    @SuppressWarnings("rawtypes")
    private String listToBalanceXML(List list, long total, int pageNo, int pageSize) {
        Document root = null;
        root = DocumentHelper.createDocument();
        Element element = root.addElement("service");
        element.addElement("name").setText("余额查询");
        element.addElement("type").setText("发布服务");
        element.addElement("total").setText(StringUtil.convertToString(total));
        element.addElement("pageNo").setText(StringUtil.convertToString(pageNo));
        element.addElement("pageSize").setText(StringUtil.convertToString(pageSize));
        Element datalist = element.addElement("datalist");
        for (int i = 0; i < list.size(); i++) {
           //Object[] obj = (Object[]) list.get(i);
            AccountBalances accountBalances = (AccountBalances) list.get(i);
            Element data = datalist.addElement("data");
            data.addElement("mdsBalancesId").setText(StringUtil.convertToString(accountBalances.getMdsBalancesId()));
            data.addElement("codeCombinationId").setText(StringUtil.convertToString(accountBalances.getCodeCombinationId()));
            data.addElement("currencyCode").setText(StringUtil.convertToString(accountBalances.getCurrencyCode()));
            data.addElement("periodName").setText(StringUtil.convertToString(accountBalances.getPeriodName()));
            data.addElement("periodType").setText(StringUtil.convertToString(accountBalances.getPeriodType()));
            data.addElement("periodNetDr").setText(StringUtil.convertToString(accountBalances.getPeriodNetDr()));
            data.addElement("periodNetCr").setText(StringUtil.convertToString(accountBalances.getPeriodNetCr()));
            data.addElement("beginBalanceDr").setText(StringUtil.convertToString(accountBalances.getBeginBalanceDr()));
            data.addElement("beginBalanceCr").setText(StringUtil.convertToString(accountBalances.getBeginBalanceCr()));
            data.addElement("endBalance").setText(StringUtil.convertToString(accountBalances.getEndBalance()));
        }
        return root.asXML();
    }

}
